package com.jar.exercise.网络编程.TCP连接.客服端和服务端;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 客户端并发上传文件，用到多线程
 */
class FileThread implements Runnable {
	private Socket socket;

	public FileThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		BufferedInputStream bis;
		OutputStream os;
		try {
			long l = System.currentTimeMillis();
			File file = new File("d:/" + l + ".png");
			bis = new BufferedInputStream(socket.getInputStream());
			OutputStream bos = new FileOutputStream(file);
			os = socket.getOutputStream();
			byte[] b = new byte[1024];
			int len;
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
			}
			os.write("我已收到文件".getBytes());
			bos.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Server6 {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(12000);
		while (true) {
			Socket socket = serverSocket.accept();
			new Thread(new FileThread(socket)).start();
		}

	}
}

class Client6 {
	public static void main(String[] args) throws IOException {
		Socket socket = new Socket("192.168.234.1", 12000);
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("d:/person_1.png")));
		OutputStream bos = socket.getOutputStream();
		int len;
		byte[] b = new byte[1024];
		while ((len = bis.read(b)) != -1) {
			bos.write(b, 0, len);
		}
		socket.shutdownOutput();
		InputStream inputStream = socket.getInputStream();
		byte[] bb = new byte[1024];
		int read = inputStream.read(bb);
		System.out.println("服务器：" + new String(bb, 0, read));
		bos.flush();
		bis.close();
		socket.close();
	}
}
